/**
 *
 */
package com.zhuoyue.elmt.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eit.eitsite.common.utils.DateUtils;
import com.eit.eitsite.modules.sys.utils.DictUtils;
import com.eit.eitsite.modules.sys.utils.UserUtils;
import com.google.gson.JsonObject;
import com.zhuoyue.elmt.Constants;
import com.zhuoyue.elmt.UserFilterUtils;
import com.zhuoyue.elmt.data.ResultData;
import com.zhuoyue.elmt.entity.DeviceParameters;
import com.zhuoyue.elmt.entity.MaintenanceStaff;
import com.zhuoyue.elmt.entity.MaintenanceStaffDevice;
import com.zhuoyue.elmt.push.PushFaultRecord;
import com.zhuoyue.elmt.service.DeviceParametersService;
import com.zhuoyue.elmt.service.MaintenanceStaffDeviceService;
import com.zhuoyue.elmt.service.MaintenanceStaffService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.eit.eitsite.common.config.Global;
import com.eit.eitsite.common.persistence.Page;
import com.eit.eitsite.common.web.BaseController;
import com.eit.eitsite.common.utils.StringUtils;
import com.zhuoyue.elmt.entity.WbFaultComplaints;
import com.zhuoyue.elmt.service.WbFaultComplaintsService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 故障投诉Controller
 * @author ChenHao
 * @version 2017-01-13
 */
@Controller
@RequestMapping(value = "${adminPath}/elmt/wbFaultComplaints")
public class WbFaultComplaintsController extends BaseController {

	@Autowired
	private WbFaultComplaintsService wbFaultComplaintsService;
	@Autowired
	private MaintenanceStaffDeviceService maintenanceStaffDeviceService;
	@Autowired
	private MaintenanceStaffService maintenanceStaffService;
	@Autowired
	private DeviceParametersService deviceParametersService;

	@ModelAttribute
	public WbFaultComplaints get(@RequestParam(required=false) String id) {
		WbFaultComplaints entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = wbFaultComplaintsService.get(id);
		}
		if (entity == null){
			entity = new WbFaultComplaints();
		}
		return entity;
	}

	@RequiresPermissions("elmt:wbFaultComplaints:view")
	@RequestMapping(value = {"list", ""})
	public String list(WbFaultComplaints wbFaultComplaints, HttpServletRequest request, HttpServletResponse response, Model model) {
		wbFaultComplaints.setMaintenUnitCode(UserUtils.getUser().getCompany().getCode());
		Page<WbFaultComplaints> page = wbFaultComplaintsService.findPage(new Page<WbFaultComplaints>(request, response), wbFaultComplaints);
		model.addAttribute("page", page);
		return "zhuoyue/elmt/wbFaultComplaintsList";
	}

	@RequiresPermissions("elmt:wbFaultComplaints:view")
	@RequestMapping(value = "form")
	public String form(WbFaultComplaints wbFaultComplaints, Model model) {
		model.addAttribute("wbFaultComplaints", wbFaultComplaints);
		return "zhuoyue/elmt/wbFaultComplaintsForm";
	}

	@RequiresPermissions("elmt:wbFaultComplaints:edit")
	@RequestMapping(value = "save")
    public String save(WbFaultComplaints wbFaultComplaints, Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, wbFaultComplaints)) {
            return form(wbFaultComplaints, model);
        }
        // 设备ID、设备注册代码、故障类型、故障时间、是否困人、困人数、脱困状态、故障处理状态、维保单位、责任人、推送时间
        // 根据设备获得维保人员列表
        MaintenanceStaff qrtyMintenanceStaff = new MaintenanceStaff();
        qrtyMintenanceStaff.setDeviceCode(wbFaultComplaints.getDeviceCode());
        qrtyMintenanceStaff.setWbdwdm(UserUtils.getUser().getCompany().getCode());
        List<MaintenanceStaff> maintenanceStaffList = maintenanceStaffService.findDeviceMainStaffList(qrtyMintenanceStaff);
        if (null != maintenanceStaffList && maintenanceStaffList.size() > 0) {
            MaintenanceStaff deviceMaintenanceStaff = maintenanceStaffList.get(0);
            wbFaultComplaints.setMaintenanceStaff(deviceMaintenanceStaff.getId());
            wbFaultComplaints.setStaffName(deviceMaintenanceStaff.getStaffName());
            wbFaultComplaints.setStaffLoginname(deviceMaintenanceStaff.getLoginName());
        }
        wbFaultComplaints.setMaintenUnitCode(UserUtils.getUser().getCompany().getCode());
        wbFaultComplaints.setCreatedBy(UserUtils.getUser().getLoginName());
        wbFaultComplaints.setCreationDate(new Date());
        wbFaultComplaints.setFaultState("1");
        wbFaultComplaintsService.save(wbFaultComplaints);
        if (StringUtils.isEmpty(wbFaultComplaints.getId())) {
            addMessage(redirectAttributes, "保存故障投诉成功");
        } else {
            addMessage(redirectAttributes, "修改故障投诉成功");
        }
        redirectAttributes.addAttribute("id", wbFaultComplaints.getId());
        return "redirect:" + Global.getAdminPath() + "/elmt/wbFaultComplaints/form?repage";
    }

	@RequiresPermissions("elmt:wbFaultComplaints:edit")
	@RequestMapping(value = "delete")
	public String delete(WbFaultComplaints wbFaultComplaints, RedirectAttributes redirectAttributes) {
		wbFaultComplaintsService.delete(wbFaultComplaints);
		addMessage(redirectAttributes, "删除故障投诉成功");
		return "redirect:"+Global.getAdminPath()+"/elmt/wbFaultComplaints/?repage";
	}

	@RequestMapping(value = {"mobilelist"})
	public String mobilelist(WbFaultComplaints wbFaultComplaints, HttpServletRequest request, HttpServletResponse response, Model model) {
		ResultData<List<WbFaultComplaints>> resultData = new ResultData();
		try {
			logger.info("查询故障投诉");

			// 设置维保人员和维保单位代码过滤条件
			wbFaultComplaints.setStaffLoginname(UserFilterUtils.getMainStaff());
			wbFaultComplaints.setMaintenUnitCode(UserFilterUtils.getMainUnitCode());
			wbFaultComplaints.setFaultState(Constants.WbFaultComplaints.FAULT_STATE_SUBMIT);

			List<WbFaultComplaints> list = wbFaultComplaintsService.findList(wbFaultComplaints);
			if (null != list) {
				resultData.setList(list);
			}
			resultData.setCode("SUCC");
			resultData.setMessage("");
		} catch (Exception e) {
			resultData.setCode("FAIL");
			resultData.setMessage("故障投诉查询出现异常！");
			e.printStackTrace();
		}
		return super.renderString(response, resultData);
	}

	@RequestMapping(method = RequestMethod.GET, value = "/mobileget/{id}")
	public String mobileget(@PathVariable String id, HttpServletResponse response) {
		ResultData<List<WbFaultComplaints>> resultData = new ResultData();
		List<WbFaultComplaints> list = new ArrayList();
		try {
			logger.info("获取单个故障投诉");
			WbFaultComplaints wbFaultComplaints = wbFaultComplaintsService.get(id);
			if (wbFaultComplaints != null) {
				list.add(wbFaultComplaints);
				resultData.setCode("SUCC");
				resultData.setMessage("SUCCESS");
			} else {
				resultData.setCode("FAIL");
				resultData.setMessage("没有查询到符合条件的故障投诉！");
			}
			resultData.setList(list);
		} catch (Exception e) {
			resultData.setCode("FAIL");
			resultData.setMessage("故障投诉查询出现异常！");
			e.printStackTrace();
		}
		return super.renderString(response, resultData);
	}

	@RequiresPermissions("elmt:wbFaultComplaints:edit")
	@RequestMapping(value = "faultComplaintsPush")
	public String faultComplaintsPush(WbFaultComplaints wbFaultComplaints, Model model, RedirectAttributes redirectAttributes) {
		String failureStatus = wbFaultComplaints.getFailureStatus() == null ? "" : wbFaultComplaints.getFailureStatus();
		String trappedPeople = wbFaultComplaints.getTrappedPeople() == null ? "" : wbFaultComplaints.getTrappedPeople();
		String trappedNumber = wbFaultComplaints.getTrappedNumber() == null ? "0" : wbFaultComplaints.getTrappedNumber();
		String outDifficulty = wbFaultComplaints.getOutDifficulty() == null ? "" : wbFaultComplaints.getOutDifficulty();
		//System.out.println("======================>>>设备ID：" + wbFaultComplaints.getDeviceNo());
		String content = "设备ID：" + wbFaultComplaints.getDeviceNo() + "设备注册代码：" + wbFaultComplaints.getDeviceCode() + "设备所在地点：" +
				wbFaultComplaints.getDeviceAddr() + "故障报告时间：" + DateUtils.formatDate(wbFaultComplaints.getReportTime(), "yyyy-MM-dd HH:mm:ss") + "故障状态：" + DictUtils.getDictLabel(failureStatus, "FAILURE_STATUS", "") +
				"是否困人：" + DictUtils.getDictLabel(trappedPeople, "yes_no", "") + "困人数：" + trappedNumber + "脱困状态：" + DictUtils.getDictLabel(outDifficulty, "OUT_DIFFICULTY", "") + "维保单位：" +
				wbFaultComplaints.getMaintenanceUnitName() + "责任人：" + wbFaultComplaints.getStaffName() + "推送时间：" + DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");

		JsonObject jsonExtra = new JsonObject();
		jsonExtra.addProperty("deviceNo", wbFaultComplaints.getDeviceNo());
		jsonExtra.addProperty("deviceCode", wbFaultComplaints.getDeviceCode());
		jsonExtra.addProperty("deviceAddr", wbFaultComplaints.getDeviceAddr());
		jsonExtra.addProperty("reportTime", DateUtils.formatDate(wbFaultComplaints.getReportTime(), "yyyy-MM-dd HH:mm:ss"));
		jsonExtra.addProperty("status", DictUtils.getDictLabel(failureStatus, "FAILURE_STATUS", ""));
		jsonExtra.addProperty("trappedPeople", DictUtils.getDictLabel(trappedPeople, "yes_no", ""));
		jsonExtra.addProperty("trappedNumber", trappedNumber);
		jsonExtra.addProperty("outDifficulty", DictUtils.getDictLabel(outDifficulty, "OUT_DIFFICULTY", ""));
		jsonExtra.addProperty("maintenanceUnitName", wbFaultComplaints.getMaintenanceUnitName());
		jsonExtra.addProperty("staffName", wbFaultComplaints.getStaffName());
		jsonExtra.addProperty("pushDate", DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
		int result = PushFaultRecord.sendToAllAndroid("电梯故障记录", "极光", content, jsonExtra.toString());
		if(result == 1){
			wbFaultComplaints.setFaultState("2");
			wbFaultComplaintsService.modifyFaultState(wbFaultComplaints);
			addMessage(redirectAttributes, "提交故障投诉成功");
		} else {
			addMessage(redirectAttributes, "提交故障投诉失败");
		}
		return "redirect:" + Global.getAdminPath() + "/elmt/wbFaultComplaints/?repage";
	}
}